import os
import sys

# 1. 手动输入设备编号
# source_dir = input("请输入日志文件根目录: ").strip()
# desti_file = input("请输入目标文件路径: ").strip()

device_id = input("请输入设备编号: ").strip()
if device_id:
    print(f"查找该设备日志中: {device_id}")
else:
    print("错误：设备编号不能为空！")

# 2. 将日志文件重命名
# folder_path = r"D:\work\scripts\logs"
# def remame_folderfiles(folder_path):
#     for filename in os.listdir(folder_path):


# 3. 将所有指定设备编号的日志读取出来并存到log_file中去
def get_logs(source_file, desti_file):
    with open(source_file, encoding="utf-8") as f:
        for line in f:  # 逐行迭代，不一次性加载全部内容
            pos = line.find(device_id)
            if pos != -1:  # 找到字符串
                with open(desti_file, 'a', encoding='utf-8') as f_b:
                    f_b.write(line)

def get_logs_from_dir(dir_path, desti_file):
    all_items = os.listdir(dir_path)
    files = [item for item in all_items if os.path.isfile(os.path.join(dir_path, item))]
    for file in files:
        file_path = os.path.join(dir_path, file)
        get_logs(file_path, desti_file)

def get_logs_from_home(dir_path, desti_file):
    
    subfolders = [
        item for item in os.listdir(dir_path)
        if os.path.isdir(os.path.join(dir_path, item))
    ]

    for folder in subfolders:
        sub_dir_path = os.path.join(dir_path, folder)
        get_logs_from_dir(sub_dir_path, desti_file)

source_dir_0 = r"D:\work\scripts\logs\New folder"
source_dir_1 = r"D:\work\scripts\logs\New folder2"
desti_file = r"D:\work\scripts\logs\log_file.txt"
get_logs_from_home(source_dir_0, desti_file)
get_logs_from_home(source_dir_1, desti_file)

# get_logs_from_home(source_dir, desti_file)
    
# 4. 根据时间戳将log_file中的日志排序
def reline(file_name):
    with open(file_name, encoding="utf-8") as f:
        lines = f.readlines()
        sorted_lines = sorted(lines, key=lambda x: x[:19])  
        with open(file_name, 'w') as f:
            f.writelines(sorted_lines)

reline(desti_file)